// src/pages/Profile.js - 用户中心 (合并了个人资料和用户面板功能)

import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import {
  Typography, Card, Row, Col, Avatar, Statistic, Progress, Space, Tag,
  Tabs, List, Button, Modal, Form, Input, message, Badge, Tooltip,
  Descriptions, Timeline, Alert, Divider, Table, Empty, notification,
  Popconfirm, InputNumber, Slider
} from 'antd';
import {
  UserOutlined, StarOutlined, TrophyOutlined, CloudUploadOutlined,
  DownloadOutlined, GiftOutlined, FireOutlined, CrownOutlined,
  CalendarOutlined, SettingOutlined, EditOutlined, EyeOutlined,
  LikeOutlined, CommentOutlined, ShareAltOutlined, ArrowUpOutlined,
  ArrowDownOutlined, FileOutlined, CopyOutlined, DeleteOutlined,
  LockOutlined, KeyOutlined, HistoryOutlined, TeamOutlined,
  LogoutOutlined, HomeOutlined, UploadOutlined,
  CheckCircleOutlined, ClockCircleOutlined, SwapOutlined
} from '@ant-design/icons';
import { points, torrents, users, auth } from '../services';
import * as invites from '../services/invites';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

const Profile = ({ setIsLoggedIn }) => {
  const navigate = useNavigate();
  const { userId } = useParams();
  const [userProfile, setUserProfile] = useState(null);
  const [userPoints, setUserPoints] = useState(null);
  const [userTorrents, setUserTorrents] = useState([]);
  const [userStats, setUserStats] = useState(null);
  const [downloadedTorrents, setDownloadedTorrents] = useState([]);
  const [inviteCodes, setInviteCodes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [messageApi, contextHolder] = message.useMessage();
  const [currentUser, setCurrentUser] = useState(null);
  const [inviteCodeModalVisible, setInviteCodeModalVisible] = useState(false);
  const [generatingCode, setGeneratingCode] = useState(false);
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);
  const [passwordForm] = Form.useForm();
  const [changingPassword, setChangingPassword] = useState(false);
  const [isSigningIn, setIsSigningIn] = useState(false);
  const [lastSignInDate, setLastSignInDate] = useState(null);
  const [canSignIn, setCanSignIn] = useState(true);

  // 魔力值兑换相关状态
  const [isExchangeModalVisible, setIsExchangeModalVisible] = useState(false);
  const [exchangeMagicAmount, setExchangeMagicAmount] = useState(100);
  const [isExchanging, setIsExchanging] = useState(false);
  const [exchangeRate] = useState(10240); // 1魔力值 = 10240字节 (10KB)

  // 用户等级配置
  const userTiers = [
    { level: 'V1', title: '新手', minLikes: 0, color: '#666', icon: UserOutlined },
    { level: 'V2', title: '铜牌', minLikes: 10, color: '#cd7f32', icon: TrophyOutlined },
    { level: 'V3', title: '银牌', minLikes: 50, color: '#c0c0c0', icon: TrophyOutlined },
    { level: 'V4', title: '金牌', minLikes: 100, color: '#ffd700', icon: TrophyOutlined },
    { level: 'V5', title: '钻石', minLikes: 500, color: '#b9f2ff', icon: CrownOutlined },
    { level: 'V6', title: '传奇', minLikes: 1000, color: '#ff6b6b', icon: CrownOutlined }
  ];

  useEffect(() => {
    loadCurrentUser();
  }, []);

  useEffect(() => {
    if (currentUser) {
      loadProfile();
    }
  }, [userId, currentUser]);

  const loadCurrentUser = () => {
    try {
      const userStr = localStorage.getItem('starrypt_user');

      if (!userStr) {
        setCurrentUser(null);
        return;
      }

      const user = JSON.parse(userStr);

      // 检查用户对象是否有效
      if (!user || typeof user !== 'object' || !user.username) {
        setCurrentUser(null);
        return;
      }

      setCurrentUser(user);
    } catch (error) {
      console.error('解析用户数据失败:', error);
      setCurrentUser(null);
    }
  };

  const loadProfile = async () => {
    try {
      setLoading(true);

      const targetUsername = userId || currentUser?.username;

      if (!targetUsername) {
        messageApi.error('请先登录');
        navigate('/login');
        return;
      }

      // 加载用户基本信息
      let users_data = JSON.parse(localStorage.getItem('starrypt_users') || '[]');
      let user = users_data.find(u => u.username === targetUsername);

      // 如果用户不存在，且目标用户是当前登录用户，自动创建用户记录
      if (!user && targetUsername === currentUser?.username) {
        const newUser = {
          username: targetUsername,
          email: `${targetUsername}@pku.edu.cn`,
          registerDate: new Date().toISOString(),
          uploadCount: 0,
          downloadCount: 0,
          ratio: 1.0,
          registerType: 'auto'
        };
        users_data.push(newUser);
        localStorage.setItem('starrypt_users', JSON.stringify(users_data));
        user = newUser;
      }

      if (!user) {
        messageApi.error('用户不存在');
        return;
      }

      setUserProfile(user);

      // 使用新的API获取用户统计数据
      if (targetUsername === currentUser?.username) {
        let profileStatsResponse = null;

        try {
          profileStatsResponse = await users.getUserProfileStats();

          if (profileStatsResponse.success) {
            const stats = profileStatsResponse.data;

            // 设置用户积分信息
            setUserPoints({
              magicValue: stats.magicValue,
              shareRatio: stats.shareRatio,
              uploadVolume: stats.uploadVolume,
              downloadVolume: stats.downloadVolume
            });

            // 设置用户统计数据
            setUserStats({
              uploadCount: stats.uploadVolume,
              downloadCount: stats.downloadVolume,
              ratio: stats.shareRatio,
              uploadedTorrents: stats.seedCount,
              downloadedTorrents: 0, // 需要额外接口获取
              registerDays: stats.registerDays,
              lastActive: new Date().toISOString()
            });

            console.log('📊 用户统计数据已加载:', stats);
          } else {
            console.warn('获取用户统计数据失败:', profileStatsResponse.message);
            throw new Error(profileStatsResponse.message);
          }
        } catch (error) {
          console.warn('获取用户统计数据失败，使用默认值:', error);
          // 设置默认值
          setUserPoints({
            magicValue: 0,
            shareRatio: 1.0,
            uploadVolume: 0,
            downloadVolume: 0
          });
        }

        // 使用auth/me接口中的signed参数检查签到状态
        if (profileStatsResponse && profileStatsResponse.success && profileStatsResponse.data.signed !== undefined) {
          const hasSigned = profileStatsResponse.data.signed;
          setCanSignIn(!hasSigned);

          // 如果今日已签到，记录本地签到状态
          if (hasSigned) {
            const today = new Date().toDateString();
            localStorage.setItem('starrypt_last_signin', today);
            setLastSignInDate(today);
          }
          console.log('🎯 签到状态已加载 (来自auth/me):', hasSigned ? '今日已签到' : '今日未签到');
        } else {
          console.warn('auth/me接口未返回签到状态，回退到本地存储检查');
          // 回退到本地存储检查
          const today = new Date().toDateString();
          const lastSignInDate = localStorage.getItem('starrypt_last_signin');
          setLastSignInDate(lastSignInDate);
          setCanSignIn(lastSignInDate !== today);
        }

        // 获取用户积分信息
        const pointsResponse = await points.getUserPoints(targetUsername);
        if (pointsResponse.success) {
          const pointsData = pointsResponse.data.points || pointsResponse.data;
          console.log('📊 积分数据已加载:', pointsData);
        } else {
          console.warn('获取积分数据失败:', pointsResponse.message);
        }
      }

      // 如果是查看自己的资料，加载用户上传的种子
      if (targetUsername === currentUser?.username) {
        try {
          const userUploadsResponse = await users.getUserUploads(targetUsername);
          if (userUploadsResponse.success) {
            const userTorrentsList = userUploadsResponse.data.torrents || [];
            setUserTorrents(userTorrentsList);

            // 如果使用了本地存储，显示提示信息
            if (userUploadsResponse.data.isLocalStorage) {
              console.log('📦 使用本地存储数据显示我的上传');
            } else {
              console.log('🔗 成功从后端API获取我的上传数据');
            }
          } else {
            console.warn('获取用户上传种子失败:', userUploadsResponse.message);
            setUserTorrents([]);
          }
        } catch (error) {
          console.error('加载用户上传种子出错:', error);
          setUserTorrents([]);
        }
      } else {
        // 查看其他用户时，使用原有的方式（从所有种子中筛选）
        const torrentsResponse = await torrents.getTorrents();
        if (torrentsResponse.success) {
          const userTorrentsList = (torrentsResponse.data.torrents || [])
            .filter(torrent => torrent.uploader === user.username)
            .sort((a, b) => new Date(b.uploadDate || b.uploadTime) - new Date(a.uploadDate || a.uploadTime));
          setUserTorrents(userTorrentsList);
        }
      }

      // 如果是查看自己的资料，加载更多数据
      if (targetUsername === currentUser?.username) {
        // 获取用户下载历史
        const downloadsResponse = await users.getUserDownloads(targetUsername);
        if (downloadsResponse.success && downloadsResponse.data?.downloads) {
          setDownloadedTorrents(downloadsResponse.data.downloads);
        }

        // 获取用户邀请码
        const invitesResponse = await invites.getUserInviteCodes();
        if (invitesResponse.success && invitesResponse.data?.inviteCodes) {
          setInviteCodes(invitesResponse.data.inviteCodes);
        }
      }

    } catch (error) {
      console.error('加载用户资料失败:', error);
      messageApi.error('加载用户资料失败: ' + error.message);
      // 设置默认值避免一直加载
      setUserPoints({
        magicValue: 0,
        shareRatio: 1.0,
        uploadVolume: 0,
        downloadVolume: 0
      });
    } finally {
      setLoading(false);
    }
  };

  const getUserRank = (ratio) => {
    if (ratio >= 5) return '钻石';
    if (ratio >= 3) return '金牌';
    if (ratio >= 1.5) return '银牌';
    if (ratio >= 1) return '铜牌';
    return '见习';
  };

  const getUserRankColor = (ratio) => {
    if (ratio >= 5) return '#2C65FF';
    if (ratio >= 3) return '#ffd700';
    if (ratio >= 1.5) return '#c0c0c0';
    if (ratio >= 1) return '#cd7f32';
    return '#a9a9a9';
  };

  const formatSize = (sizeInput) => {
    // 转换为数字
    const size = Number(sizeInput);
    if (!size || isNaN(size) || size <= 0) return '0 B';

    // 如果输入的是字节数
    if (size < 1024) {
      return `${size} B`;
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else if (size < 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    } else if (size < 1024 * 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
    } else {
      return `${(size / (1024 * 1024 * 1024 * 1024)).toFixed(2)} TB`;
    }
  };

  const formatTime = (timeString) => {
    return new Date(timeString).toLocaleString();
  };

  // 生成新邀请码
  const handleGenerateInviteCode = async () => {
    setGeneratingCode(true);

    try {
      const response = await invites.generateInviteCode();

      if (response.success && response.data?.inviteCode) {
        messageApi.success('邀请码生成成功！');
        // 刷新邀请码列表
        setInviteCodes([...inviteCodes, response.data.inviteCode]);
      } else {
        messageApi.error(response.message || '邀请码生成失败');
      }
    } catch (error) {
      console.error('生成邀请码失败:', error);
      messageApi.error('生成邀请码失败: ' + error.message);
    } finally {
      setGeneratingCode(false);
    }
  };

  // 复制邀请码到剪贴板
  const copyToClipboard = (text, domain) => {
    navigator.clipboard.writeText(text).then(
      () => {
        notification.success({
          message: '邀请码已复制到剪贴板',
          description: (
            <div>
              <p>您已成功复制邀请码: <b>{text}</b></p>
              <p style={{ color: '#ff4d4f' }}>提醒：此邀请码仅限 <b>@{domain}</b> 域名邮箱用户使用!</p>
            </div>
          ),
          duration: 5,
          placement: 'topRight',
        });
      },
      () => {
        messageApi.error('复制失败，请手动复制');
      }
    );
  };

  // 删除邀请码
  const handleDeleteInviteCode = async (code) => {
    try {
      const response = await invites.deleteInviteCode(code);

      if (response.success) {
        messageApi.success('邀请码删除成功');
        // 更新邀请码列表
        setInviteCodes(inviteCodes.filter(item => item.code !== code));
      } else {
        messageApi.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除邀请码失败:', error);
      messageApi.error('删除邀请码失败: ' + error.message);
    }
  };

  // 处理修改密码
  const handleChangePassword = async (values) => {
    setChangingPassword(true);
    try {
      // 调用users服务更新密码
      const response = await users.updatePassword(values.oldPassword, values.newPassword);

      if (response.code === 200) {
        messageApi.success('密码修改成功！');
        setIsPasswordModalVisible(false);
        passwordForm.resetFields();
      } else {
        messageApi.error(response.message || '密码修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      messageApi.error('修改密码失败: ' + (error.message || '未知错误'));
    } finally {
      setChangingPassword(false);
    }
  };

  // 每日签到处理
  const handleDailySignIn = async () => {
    if (!canSignIn || isSigningIn) return;

    setIsSigningIn(true);
    try {
      const currentUser = JSON.parse(localStorage.getItem('starrypt_user') || '{}');
      if (!currentUser.username) {
        messageApi.error('请先登录');
        return;
      }

      // 调用签到API
      const response = await points.dailySignIn(currentUser.username);
      if (response.success) {
        messageApi.success(response.message || '签到成功！获得40魔力值');
        // 更新用户积分
        setUserPoints(prev => ({
          ...prev,
          magicValue: (prev.magicValue || 0) + 40  // 增加40魔力值
        }));

        // 更新签到状态
        const today = new Date().toDateString();
        localStorage.setItem('starrypt_last_signin', today);
        setLastSignInDate(today);
        setCanSignIn(false);

        // 显示签到成功通知
        notification.success({
          message: '签到成功！',
          description: '恭喜您获得40魔力值奖励，明天记得继续签到哦！',
          placement: 'topRight',
          duration: 3
        });

        // 重新加载用户数据
        await loadProfile();
      } else {
        messageApi.error(response.message || '签到失败，请稍后重试');
      }
    } catch (error) {
      console.error('签到失败:', error);
      messageApi.error('签到失败: ' + error.message);
    } finally {
      setIsSigningIn(false);
    }
  };

  // 登出处理
  const handleLogout = async () => {
    try {
      const response = await auth.logout();
      if (response.success) {
        if (setIsLoggedIn) {
          setIsLoggedIn(false);
        }
        messageApi.success('登出成功');
        navigate('/login');
      } else {
        messageApi.error(response.message || '登出失败');
      }
    } catch (error) {
      console.error('登出失败:', error);
      messageApi.error('登出出错: ' + error.message);
    }
  };

  // 魔力值兑换上传量处理函数
  const handleMagicExchange = async () => {
    if (!exchangeMagicAmount || exchangeMagicAmount <= 0) {
      messageApi.error('请输入有效的魔力值数量');
      return;
    }

    if (!userPoints || userPoints.magicValue < exchangeMagicAmount) {
      messageApi.error(`魔力值不足！当前魔力值: ${userPoints?.magicValue || 0}`);
      return;
    }

    try {
      setIsExchanging(true);
      console.log('🔄 开始魔力值兑换，数量:', exchangeMagicAmount);

      // 调用兑换API
      const result = await users.exchangeMagicForUpload(exchangeMagicAmount);

      if (result.success) {
        // 兑换成功
        messageApi.success(`${result.message}！获得上传量: ${formatSize(result.data.uploadGained || exchangeMagicAmount * exchangeRate)}`);

        // 关闭兑换弹窗
        setIsExchangeModalVisible(false);

        // 刷新用户数据
        setTimeout(() => {
          loadProfile();
        }, 1000);

        // 显示详细的兑换结果通知
        notification.success({
          message: '魔力值兑换成功',
          description: (
            <div>
              <div>• 消耗魔力值: {result.data.magicUsed}</div>
              <div>• 获得上传量: {formatSize(result.data.uploadGained || exchangeMagicAmount * exchangeRate)}</div>
              <div>• 新魔力值余额: {result.data.newMagicBalance || (userPoints.magicValue - exchangeMagicAmount)}</div>
              <div>• 兑换比率: {result.data.exchangeRate || '1:10KB'}</div>
            </div>
          ),
          duration: 6
        });

      } else {
        // 兑换失败
        messageApi.error(result.message || '兑换失败，请重试');
        console.error('魔力值兑换失败:', result);
      }
    } catch (error) {
      console.error('魔力值兑换出错:', error);
      messageApi.error('兑换过程中出现错误: ' + error.message);
    } finally {
      setIsExchanging(false);
    }
  };

  // 打开兑换弹窗
  const showExchangeModal = () => {
    if (!userPoints || userPoints.magicValue <= 0) {
      messageApi.warning('当前魔力值不足，无法进行兑换');
      return;
    }
    setExchangeMagicAmount(Math.min(100, userPoints.magicValue)); // 默认兑换量
    setIsExchangeModalVisible(true);
  };

  // 关闭兑换弹窗
  const handleExchangeCancel = () => {
    setIsExchangeModalVisible(false);
    setExchangeMagicAmount(100);
  };

  // 表格列定义
  const uploadedColumns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <div>
          <Link to={`/torrent/${record.id}`} style={{ fontWeight: 500 }}>
            {text || record.name || '未命名种子'}
          </Link>
          {record.promotion && record.promotion !== 'none' && (
            <div style={{ marginTop: 4 }}>
              {record.promotion === 'double_upload' && (
                <Tag color="green" size="small">双倍上传</Tag>
              )}
              {record.promotion === 'free_download' && (
                <Tag color="orange" size="small">下载免费</Tag>
              )}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => {
        const getTagColor = (cat) => {
          const colorMap = {
            '电影': 'blue',
            '电视剧': 'green',
            '纪录片': 'purple',
            '动漫': 'pink',
            '音乐': 'orange',
            '图书': 'cyan',
            '软件': 'geekblue',
            '游戏': 'red'
          };
          return colorMap[cat] || 'default';
        };

        return (
          <Tag color={getTagColor(category)}>
            {category || '未分类'}
          </Tag>
        );
      },
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      render: (size) => {
        // 如果size是字符串格式的字节数，进行格式化
        if (typeof size === 'string' && /^\d+$/.test(size)) {
          const sizeInBytes = parseInt(size);
          return formatSize(sizeInBytes);
        }
        return size || '未知大小';
      },
    },
    {
      title: '做种数',
      dataIndex: 'seeders',
      key: 'seeders',
      render: (seeders) => (
        <Text style={{
          color: seeders > 100 ? '#52c41a' : seeders > 50 ? '#1890ff' : '#faad14',
          fontWeight: 500
        }}>
          <ArrowUpOutlined /> {seeders || 0}
        </Text>
      ),
    },
    {
      title: '下载数',
      dataIndex: 'leechers',
      key: 'leechers',
      render: (leechers) => (
        <Text>
          <ArrowDownOutlined /> {leechers || 0}
        </Text>
      ),
    },
    {
      title: '上传时间',
      dataIndex: 'uploadDate',
      key: 'uploadDate',
      render: (date) => {
        if (!date) return <Text type="secondary">未知时间</Text>;

        try {
          const uploadDate = new Date(date);
          const now = new Date();
          const timeDiff = now - uploadDate;
          const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

          if (daysDiff === 0) {
            return <Text style={{ color: '#52c41a' }}>今天</Text>;
          } else if (daysDiff === 1) {
            return <Text style={{ color: '#1890ff' }}>昨天</Text>;
          } else if (daysDiff < 7) {
            return <Text>{daysDiff}天前</Text>;
          } else {
            return <Text type="secondary">{uploadDate.toLocaleDateString()}</Text>;
          }
        } catch (error) {
          return <Text type="secondary">日期格式错误</Text>;
        }
      },
      sorter: (a, b) => new Date(a.uploadDate || 0) - new Date(b.uploadDate || 0),
    },
    {
      title: '完成数',
      dataIndex: 'downloads',
      key: 'downloads',
      render: (downloads) => (
        <Text style={{ color: downloads > 100 ? '#52c41a' : '#666' }}>
          <DownloadOutlined /> {downloads || 0}
        </Text>
      ),
      sorter: (a, b) => (a.downloads || 0) - (b.downloads || 0),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/torrent/${record.id}`)}
          >
            查看
          </Button>
        </Space>
      ),
    }
  ];

  const downloadedColumns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => <Link to={`/torrent/${record.torrentId}`}>{text}</Link>,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => (
        <Tag color={category === '电影' ? 'blue' : category === '电视剧' ? 'green' : 'orange'}>
          {category}
        </Tag>
      ),
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
    },
    {
      title: '下载日期',
      dataIndex: 'downloadDate',
      key: 'downloadDate',
      render: (date) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          size="small"
          icon={<DownloadOutlined />}
          onClick={() => navigate(`/torrent/${record.torrentId}`)}
        >
          重新下载
        </Button>
      ),
    },
  ];

  // 邀请码表格列定义
  const inviteCodeColumns = [
    {
      title: '邀请码',
      dataIndex: 'code',
      key: 'code',
      render: (code) => <Text copyable={{ text: code }}>{code}</Text>,
    },
    {
      title: '状态',
      dataIndex: 'used',
      key: 'used',
      render: (used) => (
        <Tag color={used ? 'default' : 'success'}>
          {used ? '已使用' : '未使用'}
        </Tag>
      ),
    },
    {
      title: '域名限制',
      dataIndex: 'emailDomain',
      key: 'emailDomain',
      render: (domain) => <Tag color="blue">@{domain}</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => new Date(date).toLocaleString(),
    },
    {
      title: '使用情况',
      key: 'usedInfo',
      render: (_, record) => (
        record.used ? (
          <span>
            被 <Text strong>{record.usedBy}</Text> 使用于 {new Date(record.usedAt).toLocaleString()}
          </span>
        ) : '未被使用'
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            icon={<CopyOutlined />}
            onClick={() => copyToClipboard(record.code, record.emailDomain)}
            title="复制邀请码"
          >
            复制
          </Button>
          {!record.used && (
            <Popconfirm
              title="确定要删除这个邀请码吗？"
              onConfirm={() => handleDeleteInviteCode(record.code)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                title="删除邀请码"
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    }
  ];

  if (loading || !userProfile || !userPoints) {
    return <div style={{ textAlign: 'center', padding: '100px 0' }}>加载中...</div>;
  }

  const isOwnProfile = !userId || userId === currentUser?.username;
  // 删除了基于总点赞的用户等级功能
  // 修复分享率为0时的显示问题：使用空值合并操作符??而不是||
  const ratio = userStats?.ratio ?? userProfile?.ratio ?? userPoints?.shareRatio ?? 1.0;
  const uploadCount = userStats?.uploadCount || userProfile.uploadCount || 0;
  const downloadCount = userStats?.downloadCount || userProfile.downloadCount || 0;
  const registerDays = userStats?.registerDays || Math.floor((new Date() - new Date(userProfile.registerDate)) / (1000 * 60 * 60 * 24));

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>

        {/* 页面标题和操作栏 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ margin: 0 }}>
            {isOwnProfile ? '个人中心' : `${userProfile.username} 的资料`}
          </Title>

          {isOwnProfile && (
            <Space>
              <Button icon={<HomeOutlined />} onClick={() => navigate('/')}>
                返回首页
              </Button>
              <Button icon={<LogoutOutlined />} onClick={handleLogout}>
                登出
              </Button>
            </Space>
          )}
        </div>

        {/* 用户信息卡片 */}
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={24}>
            <Col span={8}>
              <div style={{ textAlign: 'center', paddingTop: '35px' }}>
                <Avatar
                  size={120}
                  src={userProfile.avatar}
                  icon={<UserOutlined />}
                  style={{ marginBottom: 16 }}
                />
                <div>
                  <Title level={3} style={{ margin: 0 }}>
                    {userProfile.username}
                  </Title>
                  <Space style={{ marginTop: 8 }}>
                    <Tag color={getUserRankColor(ratio)}>
                      {getUserRank(ratio)}用户
                    </Tag>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={16}>
              {/* 用户统计数据 - 3x2网格布局 */}
              <Row gutter={[16, 16]}>
                {/* 第一行 */}
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>魔力值</span>}
                      value={userPoints.magicValue}
                      prefix={<TrophyOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: ratio >= 1.0 ?
                        'linear-gradient(135deg, #52c41a 0%, #389e0d 100%)' :
                        'linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>分享率</span>}
                      value={ratio >= 999 ? '∞' : ratio}
                      precision={ratio >= 999 ? 0 : 2}
                      prefix={<ShareAltOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: 'linear-gradient(135deg, #722ed1 0%, #531dab 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>注册天数</span>}
                      value={registerDays}
                      suffix={<span style={{ color: 'rgba(255,255,255,0.7)', fontSize: '16px' }}>天</span>}
                      prefix={<CalendarOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>

                {/* 第二行 */}
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: 'linear-gradient(135deg, #52c41a 0%, #389e0d 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>上传量</span>}
                      value={userPoints.uploadVolume}
                      prefix={<ArrowUpOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: 'linear-gradient(135deg, #1890ff 0%, #096dd9 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>下载量</span>}
                      value={userPoints.downloadVolume}
                      prefix={<ArrowDownOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card
                    size="small"
                    style={{
                      textAlign: 'center',
                      background: 'linear-gradient(135deg, #fa8c16 0%, #d46b08 100%)',
                      border: 'none',
                      borderRadius: '12px'
                    }}
                  >
                    <Statistic
                      title={<span style={{ color: 'rgba(255,255,255,0.9)', fontSize: '14px' }}>种子数量</span>}
                      value={userStats?.uploadedTorrents || userTorrents.length}
                      prefix={<FileOutlined style={{ color: 'rgba(255,255,255,0.9)' }} />}
                      valueStyle={{
                        color: '#fff',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    />
                  </Card>
                </Col>
              </Row>

              {/* 每日签到和魔力值兑换区域 */}
              {isOwnProfile && (
                <Row gutter={16} style={{ marginTop: '16px' }}>
                  {/* 每日签到区域 */}
                  <Col span={12}>
                    <Card
                      size="small"
                      style={{
                        textAlign: 'center',
                        background: canSignIn ?
                          'linear-gradient(135deg, #13c2c2 0%, #08979c 100%)' :
                          'linear-gradient(135deg, #f0f0f0 0%, #d9d9d9 100%)',
                        border: 'none',
                        borderRadius: '12px',
                        height: '140px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <div style={{ color: canSignIn ? 'white' : '#666' }}>
                        <div style={{ fontSize: '16px', marginBottom: '12px', fontWeight: 'bold' }}>
                          {canSignIn ? '🎁 每日签到' : '✅ 今日已签到'}
                        </div>
                        <Button
                          type={canSignIn ? "default" : "text"}
                          size="large"
                          icon={canSignIn ? <CheckCircleOutlined /> : <ClockCircleOutlined />}
                          loading={isSigningIn}
                          disabled={!canSignIn}
                          onClick={handleDailySignIn}
                          style={{
                            backgroundColor: canSignIn ? 'rgba(255,255,255,0.2)' : 'transparent',
                            borderColor: canSignIn ? 'rgba(255,255,255,0.3)' : 'transparent',
                            color: canSignIn ? 'white' : '#999',
                            fontWeight: 'bold',
                            fontSize: '14px',
                            height: '40px',
                            width: '100%',
                            marginBottom: '8px'
                          }}
                        >
                          {canSignIn ? '签到获得40魔力值' : '明天再来'}
                        </Button>
                        {lastSignInDate && (
                          <div style={{
                            fontSize: '12px',
                            color: canSignIn ? 'rgba(255,255,255,0.8)' : '#999'
                          }}>
                            上次签到: {new Date(lastSignInDate).toLocaleDateString()}
                          </div>
                        )}
                      </div>
                    </Card>
                  </Col>

                  {/* 魔力值兑换区域 */}
                  <Col span={12}>
                    <Card
                      size="small"
                      style={{
                        textAlign: 'center',
                        background: 'linear-gradient(135deg, #722ed1 0%, #531dab 100%)',
                        border: 'none',
                        borderRadius: '12px',
                        height: '140px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <div style={{ color: 'white' }}>
                        <div style={{ fontSize: '16px', marginBottom: '8px', fontWeight: 'bold' }}>
                          💰 魔力值兑换
                        </div>
                        <div style={{
                          fontSize: '12px',
                          marginBottom: '12px',
                          color: 'rgba(255,255,255,0.9)'
                        }}>
                          1魔力值 = 10KB上传量
                        </div>
                        <Button
                          type="default"
                          size="large"
                          icon={<SwapOutlined />}
                          onClick={showExchangeModal}
                          disabled={!userPoints || userPoints.magicValue <= 0}
                          style={{
                            backgroundColor: 'rgba(255,255,255,0.2)',
                            borderColor: 'rgba(255,255,255,0.3)',
                            color: 'white',
                            fontWeight: 'bold',
                            fontSize: '14px',
                            height: '40px',
                            width: '100%',
                            marginBottom: '8px'
                          }}
                        >
                          立即兑换
                        </Button>
                        <div style={{
                          fontSize: '12px',
                          color: 'rgba(255,255,255,0.8)'
                        }}>
                          当前魔力值: {userPoints?.magicValue || 0}
                        </div>
                      </div>
                    </Card>
                  </Col>
                </Row>
              )}
            </Col>
          </Row>
        </Card>

        {/* 标签页内容 */}
        <Tabs defaultActiveKey="1" size="large">
          {/* 概览标签页 */}
          <TabPane
            tab={
              <span>
                <TrophyOutlined />
                概览
              </span>
            }
            key="1"
          >
            {isOwnProfile && (
              <>
                {/* 快速统计卡片 */}
                <Row gutter={16} style={{ marginBottom: 24 }}>
                  <Col span={6}>
                    <Card style={{ marginBottom: 24, background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.68) 0%, rgba(118, 75, 162, 0.68) 100%)' }}>
                      <Statistic
                        title={<div style={{ color: 'yellow', fontWeight: 'bold', fontSize: '16px' }}>分享率</div>}
                        value={ratio >= 999 ? '∞' : ratio}
                        precision={ratio >= 999 ? 0 : 2}
                        valueStyle={{
                          color: 'white',
                          fontWeight: 'bold'
                        }}
                        prefix={ratio >= 1 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card style={{ marginBottom: 24, background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.68) 0%, rgba(118, 75, 162, 0.68) 100%)' }}>
                      <Statistic
                        title={<div style={{ color: 'yellow', fontWeight: 'bold', fontSize: '16px' }}>上传数</div>}
                        value={userTorrents.length}
                        valueStyle={{
                          color: 'white',
                          fontWeight: 'bold'
                        }}
                        prefix={<UploadOutlined />}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card style={{ marginBottom: 24, background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.68) 0%, rgba(118, 75, 162, 0.68) 100%)' }}>
                      <Statistic
                        title={<div style={{ color: 'yellow', fontWeight: 'bold', fontSize: '16px' }}>下载数</div>}
                        value={downloadedTorrents.length}
                        valueStyle={{
                          color: 'white',
                          fontWeight: 'bold'
                        }}
                        prefix={<DownloadOutlined />}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card
                      style={{
                        background: canSignIn ? 'linear-gradient(135deg, rgba(102, 126, 234) 0%, rgba(118, 75, 162) 100%)' : '#f5f5f5',
                        border: 'none'
                      }}
                    >
                      <div style={{ color: canSignIn ? 'white' : '#666', textAlign: 'center' }}>
                        <div style={{ fontSize: '14px', marginBottom: '8px' }}>
                          {canSignIn ? '🎁 每日签到' : '✅ 今日已签到'}
                        </div>
                        <Button
                          type={canSignIn ? "default" : "text"}
                          size="large"
                          icon={canSignIn ? <CheckCircleOutlined /> : <ClockCircleOutlined />}
                          loading={isSigningIn}
                          disabled={!canSignIn}
                          onClick={handleDailySignIn}
                          style={{
                            backgroundColor: canSignIn ? 'rgba(255,255,255,0.2)' : 'transparent',
                            borderColor: canSignIn ? 'rgba(255,255,255,0.3)' : 'transparent',
                            color: canSignIn ? 'white' : '#999',
                            fontWeight: 'bold',
                            width: '100%'
                          }}
                        >
                          {canSignIn ? '每日签到' : '明天再来'}
                        </Button>
                        {lastSignInDate && (
                          <div style={{
                            fontSize: '12px',
                            marginTop: '4px',
                            color: canSignIn ? 'rgba(255,255,255,0.8)' : '#999'
                          }}>
                            上次签到: {new Date(lastSignInDate).toLocaleDateString()}
                          </div>
                        )}
                      </div>
                    </Card>
                  </Col>
                </Row>

                {/* 签到统计信息 */}
                <Card size="small" style={{ marginBottom: 16, backgroundColor: '#fafafa' }}>
                  <Row gutter={16} align="middle">
                    <Col span={8}>
                      <Text type="secondary">
                        <CalendarOutlined style={{ marginRight: 4 }} />
                        签到状态: {canSignIn ?
                          <Tag color="orange">待签到</Tag> :
                          <Tag color="green">今日已签到</Tag>
                        }
                      </Text>
                    </Col>
                    <Col span={8}>
                      <Text type="secondary">
                        <GiftOutlined style={{ marginRight: 4 }} />
                        拥有邀请码: <strong>{inviteCodes.length}</strong> 个
                      </Text>
                    </Col>
                    <Col span={8}>
                      <Text type="secondary">
                        <TrophyOutlined style={{ marginRight: 4 }} />
                        账户等级: <Tag color={getUserRankColor(ratio)}>{getUserRank(ratio)}用户</Tag>
                      </Text>
                    </Col>
                  </Row>
                </Card>

                {/* 最近活动 */}
                {/* <Card title="最近活动" style={{ marginBottom: 16 }}>
                  <List
                    dataSource={[
                      { action: '下载了种子', item: '星际穿越 4K蓝光', time: '2小时前' },
                      { action: '上传了种子', item: '流浪地球2 4K HDR', time: '1天前' },
                    ]}
                    renderItem={item => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={<Avatar icon={<HistoryOutlined />} />}
                          title={`${item.action} "${item.item}"`}
                          description={item.time}
                        />
                      </List.Item>
                    )}
                  />
                </Card> */}
              </>
            )}

            {/* 用户基本信息 */}
            <Card title="基本信息">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="用户名" span={2}>{userProfile.username}</Descriptions.Item>
                <Descriptions.Item label="邮箱" span={2}>{userProfile.email}</Descriptions.Item>
                <Descriptions.Item label="注册日期" span={2}>{new Date(userProfile.registerDate).toLocaleString()}</Descriptions.Item>
                <Descriptions.Item label="账户等级" span={2}>
                  <Tag color={getUserRankColor(ratio)}>
                    {getUserRank(ratio)}用户
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="注册方式" span={2}>
                  {userProfile.registerType === 'invite' ? (
                    <Tag color="green">邀请注册</Tag>
                  ) : (
                    <Tag color="blue">普通注册</Tag>
                  )}
                  {userProfile.inviteCode && <span style={{ marginLeft: 8 }}>邀请码: {userProfile.inviteCode}</span>}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </TabPane>

          {/* 我的上传标签页 */}
          <TabPane
            tab={
              <span>
                <UploadOutlined />
                我的上传
                {userTorrents.length > 0 && (
                  <Badge count={userTorrents.length} style={{ marginLeft: 8 }} />
                )}
              </span>
            }
            key="2"
          >
            <Card
              title={`${isOwnProfile ? '我的' : userProfile.username + ' 的'}上传种子`}
              extra={
                isOwnProfile && (
                  <Space>
                    <Text type="secondary">
                      共 {userTorrents.length} 个种子
                    </Text>
                    <Button
                      type="primary"
                      size="small"
                      icon={<UploadOutlined />}
                      onClick={() => navigate('/upload')}
                    >
                      上传新种子
                    </Button>
                  </Space>
                )
              }
            >
              {isOwnProfile && (
                <Alert
                  message="数据来源说明"
                  description="上传种子数据来自后端 /user/upload/torrents 接口，显示您在平台上传的所有种子资源。"
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                  closable
                />
              )}

              {userTorrents.length > 0 ? (
                <Table
                  dataSource={userTorrents}
                  columns={uploadedColumns}
                  rowKey={(record) => record.id || record.title}
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) =>
                      `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
                  }}
                  scroll={{ x: 1000 }}
                />
              ) : (
                <Empty
                  description={
                    <div>
                      <div>{`${isOwnProfile ? '您' : '该用户'}还没有上传任何种子`}</div>
                      {isOwnProfile && (
                        <div style={{ marginTop: 16 }}>
                          <Button
                            type="primary"
                            icon={<UploadOutlined />}
                            onClick={() => navigate('/upload')}
                          >
                            开始上传种子
                          </Button>
                        </div>
                      )}
                    </div>
                  }
                />
              )}
            </Card>
          </TabPane>

          {/* 下载历史标签页 - 仅自己可见 */}
          {isOwnProfile && (
            <TabPane
              tab={
                <span>
                  <DownloadOutlined />
                  下载历史
                </span>
              }
              key="3"
            >
              <Card title="下载历史">
                {downloadedTorrents.length > 0 ? (
                  <Table
                    dataSource={downloadedTorrents}
                    columns={downloadedColumns}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                  />
                ) : (
                  <Empty description="暂无下载历史" />
                )}
              </Card>
            </TabPane>
          )}

          {/* 邀请码管理标签页 - 仅自己可见 */}
          {isOwnProfile && (
            <TabPane
              tab={
                <span>
                  <GiftOutlined />
                  邀请码
                </span>
              }
              key="4"
            >
              <Card
                title="邀请码管理"
                extra={
                  <Button
                    type="primary"
                    icon={<GiftOutlined />}
                    onClick={handleGenerateInviteCode}
                    loading={generatingCode}
                  >
                    生成新邀请码
                  </Button>
                }
              >
                <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                  您可以生成邀请码邀请与您相同教育机构的朋友加入星域PT站。
                  邀请码仅限与您相同邮箱域名的用户使用。
                </Paragraph>

                {inviteCodes.length > 0 ? (
                  <Table
                    dataSource={inviteCodes}
                    columns={inviteCodeColumns}
                    rowKey="code"
                    pagination={false}
                  />
                ) : (
                  <Empty description="您还没有生成任何邀请码" />
                )}
              </Card>
            </TabPane>
          )}

          {/* 账户设置标签页 - 仅自己可见 */}
          {isOwnProfile && (
            <TabPane
              tab={
                <span>
                  <SettingOutlined />
                  账户设置
                </span>
              }
              key="5"
            >
              <Card title="安全设置">
                <Button
                  type="primary"
                  icon={<LockOutlined />}
                  onClick={() => setIsPasswordModalVisible(true)}
                >
                  修改密码
                </Button>
              </Card>
            </TabPane>
          )}
        </Tabs>

        {/* 魔力值兑换模态框 */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <SwapOutlined style={{ color: '#722ed1' }} />
              <span>魔力值兑换</span>
            </div>
          }
          open={isExchangeModalVisible}
          onCancel={handleExchangeCancel}
          footer={null}
          destroyOnClose
          width={500}
        >
          <div style={{ padding: '20px 0' }}>
            {/* 当前状态展示 */}
            <Card
              size="small"
              style={{
                marginBottom: '20px',
                background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                border: '1px solid #bae6fd'
              }}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Statistic
                    title="当前魔力值"
                    value={userPoints?.magicValue || 0}
                    prefix={<TrophyOutlined style={{ color: '#722ed1' }} />}
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Col>
                <Col span={12}>
                  <Statistic
                    title="当前上传量"
                    value={userPoints?.uploadVolume || '0 B'}
                    prefix={<ArrowUpOutlined style={{ color: '#52c41a' }} />}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Col>
              </Row>
            </Card>

            {/* 兑换设置 */}
            <div style={{ marginBottom: '24px' }}>
              <div style={{ marginBottom: '20px', padding: '16px', background: 'linear-gradient(135deg, #f8faff 0%, #f0f6ff 100%)', borderRadius: '8px', border: '1px solid #e6f7ff' }}>
                <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>💎 兑换数量设置</Text>

                <div style={{ marginTop: '16px', marginBottom: '16px' }}>
                  <Text style={{ color: '#666', fontSize: '14px' }}>兑换魔力值数量：</Text>
                  <InputNumber
                    value={exchangeMagicAmount}
                    onChange={setExchangeMagicAmount}
                    min={1}
                    max={userPoints?.magicValue || 0}
                    style={{ width: '100%', marginTop: '8px' }}
                    size="large"
                    placeholder="请输入要兑换的魔力值数量"
                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\$\s?|(,*)/g, '')}
                  />
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text style={{ color: '#666', fontSize: '14px' }}>快速选择：</Text>
                  <div style={{ marginTop: '8px' }}>
                    <Space wrap>
                      {[50, 100, 200, 500, 1000].map(amount => (
                        <Button
                          key={amount}
                          size="small"
                          onClick={() => setExchangeMagicAmount(Math.min(amount, userPoints?.magicValue || 0))}
                          disabled={!userPoints || userPoints.magicValue < amount}
                          style={{
                            borderRadius: '16px',
                            background: amount <= (userPoints?.magicValue || 0) ? '#f6ffed' : undefined,
                            borderColor: amount <= (userPoints?.magicValue || 0) ? '#b7eb8f' : undefined
                          }}
                        >
                          {amount}
                        </Button>
                      ))}
                      <Button
                        size="small"
                        onClick={() => setExchangeMagicAmount(userPoints?.magicValue || 0)}
                        disabled={!userPoints || userPoints.magicValue <= 0}
                        type="dashed"
                        style={{ borderRadius: '16px' }}
                      >
                        全部
                      </Button>
                    </Space>
                  </div>
                </div>

                <div style={{ marginBottom: '8px' }}>
                  <Slider
                    value={exchangeMagicAmount}
                    onChange={setExchangeMagicAmount}
                    min={1}
                    max={userPoints?.magicValue || 100}
                    trackStyle={{ backgroundColor: '#722ed1' }}
                    handleStyle={{ borderColor: '#722ed1' }}
                    marks={{
                      1: { label: '1', style: { fontSize: '12px' } },
                      [Math.floor((userPoints?.magicValue || 100) / 4)]: { label: `${Math.floor((userPoints?.magicValue || 100) / 4)}`, style: { fontSize: '12px' } },
                      [Math.floor((userPoints?.magicValue || 100) / 2)]: { label: `${Math.floor((userPoints?.magicValue || 100) / 2)}`, style: { fontSize: '12px' } },
                      [Math.floor((userPoints?.magicValue || 100) * 3 / 4)]: { label: `${Math.floor((userPoints?.magicValue || 100) * 3 / 4)}`, style: { fontSize: '12px' } },
                      [userPoints?.magicValue || 100]: { label: `${userPoints?.magicValue || 100}`, style: { fontSize: '12px' } }
                    }}
                  />
                </div>
              </div>
            </div>

            {/* 兑换预览 */}
            <Card
              size="small"
              style={{
                marginBottom: '24px',
                background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                border: '1px solid #0ea5e9',
                borderRadius: '12px',
                boxShadow: '0 4px 12px rgba(14, 165, 233, 0.15)'
              }}
            >
              <div style={{ textAlign: 'center' }}>
                <div style={{ marginBottom: '16px' }}>
                  <Text strong style={{ fontSize: '18px', color: '#0369a1' }}>
                    ✨ 兑换预览
                  </Text>
                </div>
                <Row gutter={20}>
                  <Col span={10}>
                    <div style={{
                      textAlign: 'center',
                      padding: '12px',
                      background: 'linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%)',
                      borderRadius: '8px',
                      border: '1px solid #fca5a5'
                    }}>
                      <div style={{ color: '#dc2626', fontSize: '24px', fontWeight: 'bold' }}>
                        -{exchangeMagicAmount.toLocaleString()}
                      </div>
                      <div style={{ color: '#7f1d1d', fontSize: '13px', fontWeight: '500', marginTop: '4px' }}>
                        💰 消耗魔力值
                      </div>
                    </div>
                  </Col>
                  <Col span={4}>
                    <div style={{
                      textAlign: 'center',
                      color: '#0ea5e9',
                      fontSize: '28px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      height: '100%'
                    }}>
                      🔄
                    </div>
                  </Col>
                  <Col span={10}>
                    <div style={{
                      textAlign: 'center',
                      padding: '12px',
                      background: 'linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%)',
                      borderRadius: '8px',
                      border: '1px solid #86efac'
                    }}>
                      <div style={{ color: '#16a34a', fontSize: '24px', fontWeight: 'bold' }}>
                        +{formatSize(exchangeMagicAmount * exchangeRate)}
                      </div>
                      <div style={{ color: '#14532d', fontSize: '13px', fontWeight: '500', marginTop: '4px' }}>
                        📈 获得上传量
                      </div>
                    </div>
                  </Col>
                </Row>
                <div style={{
                  marginTop: '16px',
                  padding: '8px 16px',
                  background: 'rgba(255,255,255,0.7)',
                  borderRadius: '20px',
                  fontSize: '13px',
                  color: '#0369a1',
                  fontWeight: '600',
                  display: 'inline-block'
                }}>
                  💎 兑换比率: 1 魔力值 = 10KB 上传量
                </div>
              </div>
            </Card>

            {/* 重要提示 */}
            <Alert
              message="兑换提示"
              description={
                <div>
                  <div>• 兑换后的上传量将立即生效</div>
                  <div>• 兑换操作不可撤销，请谨慎操作</div>
                  <div>• 建议保留一定的魔力值用于日常操作</div>
                </div>
              }
              type="info"
              showIcon
              style={{ marginBottom: '20px' }}
            />

            {/* 操作按钮 */}
            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button size="large" onClick={handleExchangeCancel}>
                  取消
                </Button>
                <Button
                  type="primary"
                  size="large"
                  icon={<SwapOutlined />}
                  onClick={handleMagicExchange}
                  loading={isExchanging}
                  disabled={!exchangeMagicAmount || exchangeMagicAmount <= 0 || !userPoints || userPoints.magicValue < exchangeMagicAmount}
                >
                  确认兑换
                </Button>
              </Space>
            </div>
          </div>
        </Modal>

        {/* 修改密码模态框 */}
        <Modal
          title="修改密码"
          open={isPasswordModalVisible}
          onCancel={() => {
            setIsPasswordModalVisible(false);
            passwordForm.resetFields();
          }}
          footer={null}
          destroyOnClose
        >
          <Form
            form={passwordForm}
            layout="vertical"
            onFinish={handleChangePassword}
          >
            <Form.Item
              name="oldPassword"
              label="当前密码"
              rules={[
                { required: true, message: '请输入当前密码' }
              ]}
            >
              <Input.Password
                prefix={<KeyOutlined />}
                placeholder="请输入当前密码"
              />
            </Form.Item>

            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[
                { required: true, message: '请输入新密码' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入新密码"
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              label="确认新密码"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请再次输入新密码"
              />
            </Form.Item>

            <Divider />

            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button
                  onClick={() => {
                    setIsPasswordModalVisible(false);
                    passwordForm.resetFields();
                  }}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={changingPassword}
                  icon={<LockOutlined />}
                >
                  确认修改
                </Button>
              </Space>
            </div>
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default Profile;
